package handlers

import (
	"net/http"
	"strconv"
	"time"

	"github.com/ev-charging/cloud-platform/internal/pricing"
	"github.com/gin-gonic/gin"
)

// PricingHandler 电价API处理器
type PricingHandler struct {
	pricingEngine *pricing.PricingEngine
}

// NewPricingHandler 创建电价API处理器
func NewPricingHandler(pricingEngine *pricing.PricingEngine) *PricingHandler {
	return &PricingHandler{
		pricingEngine: pricingEngine,
	}
}

// GetCurrentRate 获取当前电价
func (h *PricingHandler) GetCurrentRate(c *gin.Context) {
	currentTime := time.Now()
	rate := h.pricingEngine.GetRateByTime(currentTime)

	c.JSON(http.StatusOK, gin.H{
		"current_rate": rate,
		"time": currentTime.Format("2006-01-02 15:04:05"),
	})
}

// GetTimeRanges 获取所有电价时间段
func (h *PricingHandler) GetTimeRanges(c *gin.Context) {
	ranges := h.pricingEngine.GetTimeRanges()
	c.JSON(http.StatusOK, gin.H{"time_ranges": ranges})
}

// CalculateCost 计算充电费用
func (h *PricingHandler) CalculateCost(c *gin.Context) {
	// 解析请求参数
	energyStr := c.PostForm("energy")
	startTimeStr := c.PostForm("start_time")
	endTimeStr := c.PostForm("end_time")

	// 验证参数
	if energyStr == "" || startTimeStr == "" || endTimeStr == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "缺少必要参数: energy, start_time, end_time"})
		return
	}

	// 转换能量值
	energy, err := strconv.ParseFloat(energyStr, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的能量值: " + err.Error()})
		return
	}

	// 解析时间
	startTime, err := time.Parse("2006-01-02 15:04:05", startTimeStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的开始时间格式(应为2006-01-02 15:04:05): " + err.Error()})
		return
	}

	endTime, err := time.Parse("2006-01-02 15:04:05", endTimeStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的结束时间格式(应为2006-01-02 15:04:05): " + err.Error()})
		return
	}

	// 计算费用
	cost, err := h.pricingEngine.CalculateCost(energy, startTime, endTime)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "计算费用失败: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"energy":      energy,
		"start_time":  startTimeStr,
		"end_time":    endTimeStr,
		"total_cost":  cost,
		"currency":    "CNY",
	})
}